//获取录音总时长
export async function getAudioDuration(mp3Url) {
    try {
        const response = await fetch(mp3Url);
        const arrayBuffer = await response.arrayBuffer();
        const audioContext = new AudioContext();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
        return audioBuffer.duration; // 返回精确时长（秒）
    } catch (err) {
        throw new Error("解析音频失败: " + err.message);
    }
}

//音频初始化
export function initAudio(url) {
    return new Promise((resolve, reject) => {
        const audio = new Audio(url);
        audio.addEventListener('loadedmetadata', () => {
            resolve(audio);
        });
        audio.addEventListener('error', (err) => {
            reject(err);
        });
    });
}

//音频转换时间
export function formatAudioTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 初始化音频实例并添加事件监听
export function setupAudioInstance(audioInstance, vm) {
    audioInstance.addEventListener('timeupdate', () => {
        if (audioInstance) {
            vm.duration = audioInstance.duration;
            vm.currentTime = audioInstance.currentTime;
            vm.progress = (vm.currentTime / vm.duration) * 100;
        }
    });
    audioInstance.addEventListener('ended', () => {
        vm.isPlaying = false;
    });
    return audioInstance;
}